package com.hapzxb.provider.controller;

import com.hapzxb.provider.bean.Department;
import com.hapzxb.provider.service.DepartmentService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.client.ServiceInstance;
import org.springframework.cloud.client.discovery.DiscoveryClient;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.List;

@RestController
@RequestMapping("/provider/department")
public class DepartmentController {
    @Autowired
    private DepartmentService service;

    @Autowired
    private DiscoveryClient client;

    @PostMapping("/save")
    public boolean saveHandle(@RequestBody Department department) {
        department.setDbase("test");
        return service.saveDepartment(department);
    }

    @PostMapping("/del/{id}")
    public boolean delHandle(@PathVariable("id") int id) {
        return service.removeDepartment(id);
    }

    @PostMapping("/update")
    public boolean updateHandle(@RequestBody Department department) {
        department.setDbase("test");
        return service.modifyDepart(department);
    }

    @PostMapping("/get/{id}")
    public Department getHandle(@PathVariable("id") int id) {
        return service.getDepartmentById(id);
    }

    @PostMapping("/list")
    public List<Department> listHandle() {
        return service.listAllDepartment();
    }

    @GetMapping("/discovery")
    public Object discoveryHandle() {
        // 获取服务注册列表中所有微服务 名称
        List<String> springApplicationNames = client.getServices();
        for (String name : springApplicationNames) {
            // 获取提供指定微服务名称服务的 所有提供者主机
            List<ServiceInstance> instances = client.getInstances(name);
            for (ServiceInstance instance : instances) {
                String host = instance.getHost();
                int port = instance.getPort();
                System.out.println(host + ":" + port);
            }
        }
        return springApplicationNames;
    }
}
